package com.hellobike.haxing.modules.shop.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.system.vo.LoginUser;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.order.constant.OrderConstants;
import com.hellobike.haxing.modules.shop.entity.ShopWithdrew;
import com.hellobike.haxing.modules.shop.service.IShopWithdrewService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 提现申请
 * @Author: haxing-boot
 * @Date: 2020-02-08
 * @Version: V1.0
 */
@RestController
@RequestMapping("/shop/shopWithdrew")
@Slf4j
public class ShopWithdrewController extends BaseController<ShopWithdrew, IShopWithdrewService> {
    @Autowired
    private IShopWithdrewService shopWithdrewService;

    /**
     * 财务分页列表查询
     *
     * @param shopWithdrew
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "提现申请-财务分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ShopWithdrew shopWithdrew,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        QueryWrapper<ShopWithdrew> queryWrapper = QueryGenerator.initQueryWrapper(shopWithdrew, req.getParameterMap());
        if (shopWithdrew.getStatus() == null) {
            queryWrapper.lambda().notIn(ShopWithdrew::getStatus, OrderConstants.ORDER_STATUS_1);
        }
        Page<ShopWithdrew> page = new Page<>(pageNo, pageSize);
        IPage<ShopWithdrew> pageList = shopWithdrewService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 财务分页列表查询
     *
     * @param shopWithdrew
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "提现申请-运营分页列表查询")
    @GetMapping(value = "/yylist")
    public Result<?> queryYyPageList(ShopWithdrew shopWithdrew,
                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Page<ShopWithdrew> page = new Page<>(pageNo, pageSize);
        IPage<ShopWithdrew> pageList = shopWithdrewService.queryYyPage(shopWithdrew, page, req.getParameterMap());
        log.info("debug--大、>:{}", JSON.toJSONString(pageList));
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param shopWithdrew
     * @return
     */
    @AutoLog(value = "提现申请-添加", operateType = 2)
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ShopWithdrew shopWithdrew) {
        shopWithdrewService.save(shopWithdrew);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param shopWithdrew
     * @return
     */
    @AutoLog(value = "提现申请-编辑", operateType = 3)
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ShopWithdrew shopWithdrew) {
        shopWithdrewService.updateById(shopWithdrew);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "提现申请-删除", operateType = 4)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) Long id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        shopWithdrewService.delete(id, sysUser.getId());
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "提现申请-批量删除", operateType = 4)
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        shopWithdrewService.deleteBatch(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()), sysUser.getId());
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) Long id) {
        ShopWithdrew shopWithdrew = shopWithdrewService.getById(id);
        if (shopWithdrew == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(shopWithdrew);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param shopWithdrew
     */
    @AutoLog(value = "提现申请-导出excel", operateType = 6)
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ShopWithdrew shopWithdrew) {
        // Step.1 组装查询条件
        QueryWrapper<ShopWithdrew> queryWrapper = QueryGenerator.initQueryWrapper(shopWithdrew, request.getParameterMap());
        if (shopWithdrew.getStatus() == null) {
            queryWrapper.lambda().notIn(ShopWithdrew::getStatus, OrderConstants.ORDER_STATUS_1);
        }
        // Step.2 获取导出数据
        List<ShopWithdrew> pageList = shopWithdrewService.list(queryWrapper);
        pageList.forEach(record -> {
            String typeName = "下单奖励";
            if(record.getType() != null && record.getType().intValue() == 3){
                typeName = "月度达标奖励";
            } else if(record.getType() != null && record.getType().intValue() == 1){
                typeName = "佣金";
            }
            record.setTypeName(typeName);

            String statusName = "";
            if(record.getStatus() == null){
                statusName = "";
            } else {
                switch (record.getStatus()) {
                    case 1:
                        statusName = "申请中";
                        break;
                    case 2:
                        statusName = "审核通过（财务）";
                        break;
                    case 3:
                        statusName = "审核拒绝（财务）";
                        break;
                    case 4:
                        statusName = "打款成功";
                        break;
                    case 5:
                        statusName = "打款失败";
                        break;
                    case 6:
                        statusName = "打款中";
                        break;
                    case 7:
                        statusName = "审核通过（运营）";
                        break;
                    case 8:
                        statusName = "数据异常";
                        break;
                    default:
                        break;
                }
            }
            record.setStatusName(statusName);
        });

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.3 AutoPoi 导出Excel
        String title = "运营提现审核";
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, ShopWithdrew.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "提现申请-导入excel", operateType = 5)
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ShopWithdrew.class);
    }

    /**
     * 批量审核通过
     */
    @AutoLog(value = "提现申请-批量审核通过", operateType = 11)
    @RequestMapping(value = "/approveBatch")
    public Result<?> approveBatch(@RequestParam(name = "ids", required = true) String ids) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return shopWithdrewService.approveBatch(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()), sysUser.getUsername());
    }

    /**
     * 审核通过
     */
    @AutoLog(value = "提现申请-审核通过", operateType = 11)
    @RequestMapping(value = "/approve")
    public Result<?> approve(@RequestParam(name = "id", required = true) Long id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return shopWithdrewService.approve(id, sysUser.getUsername());
    }

    /**
     * 审核拒绝
     * 拒绝需退款
     */
    @AutoLog(value = "提现申请-审核拒绝", operateType = 12)
    @PutMapping(value = "/reject")
    public Result<?> reject(@RequestBody ShopWithdrew shopWithdrew) throws Exception {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        shopWithdrew.setAuditUser(sysUser.getUsername());
        return shopWithdrewService.reject(shopWithdrew);
    }

    /**
     * 打款
     */
    @AutoLog(value = "提现申请-打款", operateType = 14)
    @RequestMapping(value = "/loan")
    public Result<?> loan(@RequestParam(name = "id", required = true) Long id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return shopWithdrewService.loan(id, sysUser.getUsername());
    }

    /**
     * 批量打款
     */
    @AutoLog(value = "提现申请-批量打款", operateType = 14)
    @RequestMapping(value = "/loanBatch")
    public Result<?> loanBatch(@RequestParam(name = "ids", required = true) String ids) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        shopWithdrewService.loanBatch(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()), sysUser.getUsername());
        return Result.ok("批量打款成功!");
    }

    /**
     * 运营批量审核通过
     */
    @AutoLog(value = "提现申请-运营批量审核通过", operateType = 11)
    @RequestMapping(value = "/yyapproveBatch")
    public Result<?> yyapproveBatch(@RequestParam(name = "ids", required = true) String ids) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        shopWithdrewService.yyapproveBatch(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()), sysUser.getUsername());
        return Result.ok("批量审核通过成功!");
    }

    /**
     * 运营审核通过
     */
    @AutoLog(value = "提现申请-运营审核通过", operateType = 11)
    @RequestMapping(value = "/yyapprove")
    public Result<?> yyapprove(@RequestParam(name = "id", required = true) Long id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        shopWithdrewService.yyapprove(id, sysUser.getUsername());
        return Result.ok("审核通过成功!");
    }

    /**
     * 运营审核通过
     */
    @AutoLog(value = "提现申请-运营审核通过", operateType = 11)
    @RequestMapping(value = "/yyreject")
    public Result<?> yyreject(@RequestBody ShopWithdrew shopWithdrew) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        shopWithdrew.setAuditUser(sysUser.getUsername());
        shopWithdrewService.yyreject(shopWithdrew, shopWithdrew.getId(), sysUser.getUsername());
        return Result.ok("审核通过成功!");
    }
}
